import pymssql
import configparser
import zipfile
from bypy   import ByPy
import time
import os
import re
import threading

ver = 'Ver : 20180722'
author = 'Author : 马兵'

def DataBackup(IP, Name, Password, DataBase, Path):
    print('********************分割线*********************')
    print('%s : 开始备份数据库......'%time.ctime())
    Time = time.strftime('%Y%m%d%H%M%S')
    Path = Path + '_' + Time + '.bak'
    connect = pymssql.connect('%s'%IP,'%s'%Name,'%s'%Password,'%s'%DataBase)
    cur = connect.cursor()
    if not cur:
        raise Exception('数据库连接失败')
    connect.autocommit(True)
    cur.execute("BACKUP DATABASE %s TO  DISK = N'%s' WITH NOFORMAT, NOINIT,  NAME = N'%s-完整 数据库 备份', SKIP, NOREWIND, NOUNLOAD,  STATS = 10"%(DataBase,Path,DataBase))
    connect.autocommit(False)
    connect.commit()
    print('********************分割线*********************')
    print('%s : 数据库备份完成......'%time.ctime())
    connect.close()
    return Path

def ZipFile(File, Path):
    print('********************分割线*********************')
    print('%s : 开始压缩数据库......'%time.ctime())
    Time = time.strftime('%Y%m%d%H%M%S')
    Path = Path + '_'  + Time + '.zip'
    zip = zipfile.ZipFile(Path, 'w', zipfile.ZIP_DEFLATED)
    zip.write(File)
    print('********************分割线*********************')
    print('%s : 压缩数据库完成......'%time.ctime())
    zip.close()
    os.remove(File)
    return Path

def Get_min(lists):
    lists = sorted(lists)
    lens = len(lists)-1
    for i in range(0,lens):
        lists.pop()
    return ''.join(lists)

def FindNewFile(path, name):
    lists = os.listdir(path)
    strs = ' '.join(lists)
    res = re.compile('%s_\w*'%name)
    j = len(res.findall(strs))-1
    for i in range(0, len(res.findall(strs))-1):
        lists = os.listdir(path)
        strs = ' '.join(lists)
        res = re.compile('%s_\w*'%name)
        OldFile = path + Get_min(res.findall(strs)) + '.zip'
        os.remove(OldFile)

def Thread1(IP, Name, Password, DataBase, Path, BackupPath, Backup_Company, Backup_Cycle):
    global x
    if x == 1:
        if Backup_Company == '秒':
            Backup_Cycle = int(Backup_Cycle)
        elif Backup_Company == '分':
            Backup_Cycle = int(Backup_Cycle)*60
        elif Backup_Company == '时':
            Backup_Cycle = int(Backup_Cycle)*3600
        elif Backup_Company == '天':
            Backup_Cycle = int(Backup_Cycle)*3600*24
        elif Backup_Company == '周':
            Backup_Cycle = int(Backup_Cycle)*3600*24*7
        ZipFiles = ZipFile(DataBackup(IP, Name, Password, DataBase, Path), Path)
        FindNewFile(BackupPath, DataBase)
        x = 0
    time.sleep(Backup_Cycle)

def Thread2(DataBase, BackupPath, ProName, UpLoad_Company, UpLoad_Cycle):
    global x
    if x == 0:
        if UpLoad_Company == '秒':
            UpLoad_Cycle = int(UpLoad_Cycle)
        elif UpLoad_Company == '分':
            UpLoad_Cycle = int(UpLoad_Cycle)*60
        elif UpLoad_Company == '时':
            UpLoad_Cycle = int(UpLoad_Cycle)*3600
        elif UpLoad_Company == '天':
            UpLoad_Cycle = int(UpLoad_Cycle)*3600*24
        elif UpLoad_Company == '周':
            UpLoad_Cycle = int(UpLoad_Cycle)*3600*24*7
        lists = os.listdir(BackupPath)
        strs = ' '.join(lists)
        res = re.compile('%s_\w*'%DataBase)
        FileName = BackupPath + ''.join(res.findall(strs)) + '.zip'
        remotepath = '/' + ProName + '/' + DataBase + '_' + Time + '.zip'
        by = ByPy()
        by.mkdir(remotepath = '%s'%ProName)
        print('********************分割线*********************')
        print('%s : 开始上传数据库......'%time.ctime())
        by.upload(localpath = '%s'%FileName, remotepath = '%s'%remotepath, ondup = 'newcopy')
        print('********************分割线*********************')
        print('%s : 上传成功......'%time.ctime())
        x = 1
    time.sleep(UpLoad_Cycle)

if __name__ == '__main__':
    print(ver)
    print(author)
    x = 1
    con = threading.Condition()

    while True:
        try:
            Time = time.strftime('%Y%m%d%H%M%S')
            config = configparser.ConfigParser()
            config.read('DataBackupConfig.ini', encoding='utf-8')
            IP = config.get('SQL', 'IP')
            Name = config.get('SQL', 'Name')
            Password = config.get('SQL', 'Password')
            DataBase = config.get('SQL', 'DataBase')
            ProName = config.get('Pro','Name')
            BackupPath = config.get('Pro', 'BackupPath')
            Path = BackupPath + DataBase
            Storage_Enable = config.get('Pro', 'Storage_Enable')
            Backup_Cycle = config.get('Pro', 'Backup_Cycle')
            Backup_Company = config.get('Pro', 'Backup_Company')
            UpLoad_Cycle = config.get('Pro', 'UpLoad_Cycle')
            UpLoad_Company = config.get('Pro', 'UpLoad_Company')

            if Storage_Enable == 'True':
                #Thread1(IP, Name, Password, DataBase, Path, BackupPath, Backup_Company, Backup_Cycle)
                T1 = threading.Thread(target=Thread1, args=(IP, Name, Password, DataBase, BackupPath, BackupPath, Backup_Company, Backup_Cycle))
                T2 = threading.Thread(target=Thread2, args=(DataBase, BackupPath, ProName, UpLoad_Company, UpLoad_Cycle))
                
                T1.start()
                T2.start()
                #T1.join()
                #T2.join()

            elif Storage_Enable == 'False':
                Path= os.getcwd()
                localpath = ZipFile(DataBackup(IP, Name, Password, DataBase, Path), Path)
                remotepath = '/' + ProName + '/' + DataBase + '_' + Time + '.zip'
                by = ByPy()
                by.mkdir(remotepath = '%s'%ProName)
                print('********************分割线*********************')
                print('%s : 开始上传数据库......'%time.ctime())
                by.upload(localpath = '%s'%localpath, remotepath = '%s'%remotepath, ondup = 'newcopy')
                print('********************分割线*********************')
                print('%s : 上传成功......'%time.ctime())
                os.remove(localpath)
                print('********************分割线*********************')
                print('%s : 本地压缩文件删除成功......'%time.ctime())
            else :
                print('********************分割线*********************')
                print('请输入正确格式！！！')

        except:
            os.system('pause')
